
package nz.ac.massey.webtech.sseperformance;

import java.io.IOException;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author jens dietrich
 */
public class Async extends HttpServlet {

    @Override
    public void init() throws ServletException {
        super.init(); 
        System.out.println("starting thread pool");
        Executor executor = new ThreadPoolExecutor(20,30,5,TimeUnit.MINUTES,new LinkedBlockingQueue<Runnable>(100));
        getServletContext().setAttribute("executor", executor);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("entering async event delivery");
        
        response.setContentType("text/event-stream");
        response.setCharacterEncoding ("UTF-8");
        
        AsyncContext asyncContext = request.startAsync(request, response);
        asyncContext.setTimeout(5000);
        
           
        Executor executor = (Executor)getServletContext().getAttribute("executor");
        executor.execute(new AsyncProcessor(asyncContext));
       
    }

}
